package com.houtai.eduservice.config;

import com.houtai.eduservice.entity.EduLog;
import com.houtai.eduservice.service.EduLogService;
import com.houtai.security.security.TokenManager;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.Date;

@Aspect
@Component
@Slf4j
public class LoggerAspect {
    @Autowired
    public EduLogService eduLogService;

    @Resource
    private TokenManager tokenManager;
    /**
     * 设置操作日志切入点   在注解的位置切入代码
     */
    @Pointcut("@annotation(com.houtai.eduservice.config.OperationLogDesc)")
    public void operLogPoinCut() {
    }
    @AfterReturning(returning = "result", value = "operLogPoinCut()")
    public void saveOperLog(JoinPoint joinPoint, Object result) throws Throwable {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        try {
            //将返回值转换成map集合
            //Map<String, String> map = (Map<String, String>) result;
            EduLog operationLog = new EduLog();
            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            //获取切入点所在的方法
            Method method = signature.getMethod();
            //获取操作
            OperationLogDesc annotation = method.getAnnotation(OperationLogDesc.class);
            if (annotation != null) {
                operationLog.setModule(annotation.module());
                operationLog.setDescription(annotation.description());
            }
            //操作时间
            operationLog.setCreateTime(new Date());
            //操作用户
//            operationLog.setUserName(request.getHeader("userName"));
            String token = request.getHeader("token");
            String userName = tokenManager.getUserFromToken(token);
            operationLog.setUserName(userName);
            //操作IP
            //operationLog.setIp(IPUtil.getIpAdr(request));
            operationLog.setIp(request.getRemoteAddr());
            //返回值信息
            //operationLog.setResult(map.get("message"));
            //保存日志
            eduLogService.save(operationLog);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
